package com.wnxy.web.servlet;

import com.wnxy.entity.Employee;
import com.wnxy.service.impl.EmployeeServiceImpl;
import com.wnxy.util.DateUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

@WebServlet("/updateEmp")
public class UpdateEmpServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");//处理接收POST请求的乱码
        resp.setContentType("text/html;charset=UTF-8");//解决响应到浏览器的内容的乱码问题
        Employee emp = new Employee();
        emp.setId(Integer.parseInt(req.getParameter("id")));
        emp.setTno(req.getParameter("tno"));
        emp.setName(req.getParameter("ename"));
        emp.setGender(req.getParameter("gender"));
        Date date = DateUtil.parseDate(req.getParameter("birthday"));
        emp.setBirthday(date);
        emp.setTitle(req.getParameter("title"));
        String salarystr = req.getParameter("salary");
        BigDecimal salary = null;
        if (salarystr!=null&&!salarystr.equals("")){
            salary=new BigDecimal(salarystr);
        }
        emp.setSalary(salary);
        String managerIdstr = req.getParameter("managerId");
        Integer managerId = null;
        if(!"BOSS".equals(managerIdstr)){
            managerId = Integer.parseInt(managerIdstr);
        }
        emp.setManagerId(managerId);
        String deptIdStr = req.getParameter("deptId");
        Integer deptId = null;
        if(!"轮岗".equals(deptIdStr)){
            deptId = Integer.parseInt(deptIdStr);
        }
        emp.setDeptId(deptId);
        EmployeeServiceImpl esi = new EmployeeServiceImpl();
        boolean flag = esi.updateEmp(emp);
        if (flag){
            resp.getWriter().write("<script>alert('恭喜，修改信息成功')</script>");
        }else {
            resp.getWriter().write("<script>alert('警告，修改信息失败')</script>");
        }
        resp.setHeader("refresh","0,url="+req.getContextPath()+"/onePage");
    }
}
